package spring.test4;

import com.blackhorse.config.SpringConfiguration;
import com.blackhorse.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo3_SpringTransactionControl {
    ApplicationContext applicationContext;

    /**
     * 无事务控制的转账测试，service中有异常则数据丢失
     * 配置文件：transactionControl\tx.xml
     * Serivce：com.blackhorse.service.AccountServiceImpl
     * dao：com.blackhorse.dao.AccountDaoImplWithJdbcTemplate
     */
    @Test
    public void testAccountService() {
        String xmlPath = "transactionControl/tx.xml";
        applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        AccountService service = (AccountService) applicationContext.getBean("accountServiceImpl");
        service.transfer("张三", "李四", 100);
        System.out.println("转账完成");
    }

    /**
     * 有声明式事务控制的转账测试，service中有异常则事务回滚
     * 配置文件：transactionControl\tx.xml
     * Serivce：com.blackhorse.service.AccountServiceImpl2
     * dao：com.blackhorse.dao.AccountDaoImplWithJdbcTemplate
     */
    @Test
    public void testAccountServiceWithTx() {
        String xmlPath = "transactionControl/tx.xml";
        applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        AccountService service = (AccountService) applicationContext.getBean("accountServiceImplWithTx");
        service.transfer("张三", "李四", 100);
        System.out.println("转账完成");
    }


    /**
     * 有声明式事务控制的转账测试（注解配置），service中有异常则事务回滚
     * 配置文件：transactionControl\tx_annotation.xml
     * Serivce：com.blackhorse.service.AccountServiceImplAnno
     * dao：com.blackhorse.dao.AccountDaoImplWithJdbcTemplate
     */
    @Test
    public void testAccountServiceWithTx_Annotation() {
        String xmlPath = "transactionControl/tx_annotation.xml";
        applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        AccountService service = (AccountService) applicationContext.getBean("accountServiceImplAnno");
        service.transfer("张三", "李四", 100);
        System.out.println("转账完成");
    }

    /**
     * 有声明式事务控制的转账测试（纯注解配置），service中有异常则事务回滚
     * 配置类：com.blackhorse.config.SpringConfiguration和其他两个子配置类
     * Serivce：com.blackhorse.service.AccountServiceImplAnno
     * dao：com.blackhorse.dao.AccountDaoImplWithJdbcTemplate
     */
    @Test
    public void testAccountServiceWithTx_PureAnnotation() {
        applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        AccountService service = (AccountService) applicationContext.getBean("accountServiceImplAnno");
        service.transfer("张三", "李四", 100);
        System.out.println("转账完成");
    }

}
